package com.czh.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.czh.constants.SystemConstants;
import com.czh.domain.ResponseResult;
import com.czh.domain.vo.LocationVo;
import com.czh.domain.vo.WeatherVo;
import com.czh.enums.AppHttpCodeEnum;
import com.czh.utils.Address;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
@Slf4j
@Data
public class LocationServiceImpl {
    private String ipAddr;
    public void setIpAddr(HttpServletRequest request) {
        this.ipAddr = Address.getIpAddr(request);
    }

    public ResponseResult<LocationVo> getIpLocationInfo() {
        //地区信息
        JSONObject locationInfo = Address.getLocationInfo(ipAddr);
        //天气信息
        Object weather = locationInfo.get("adcode");
        if (ipAddr.equals(SystemConstants.LOCATION_IP)){
            weather="530402";//默认是红塔区
        }
        //这个lives是一个只有一个元素的集合，需要转化为JsonArray再取值
        JSONObject jsonObject;
        try {
            Object o = Address.getWeatherInfo((weather).toString()).get("lives");
            jsonObject= JSONArray.parseArray(o.toString()).getJSONObject(0);
        }catch (IndexOutOfBoundsException e){
            return ResponseResult.errorResult(AppHttpCodeEnum.WEATHER_ERROR);
        }

        WeatherVo weatherVo = WeatherVo.builder().weather(jsonObject.getString("weather")).temperature(jsonObject.getString("temperature"))
                .winddirection(jsonObject.getString("winddirection")).windpower(jsonObject.getString("windpower")).build();
        log.error(weatherVo.toString());
        if (ipAddr.equals(SystemConstants.LOCATION_IP)){
            return ResponseResult.okResult(LocationVo.builder()
                    .lives(weatherVo)
                    .province(null)
                    .city(null).build());
        }
        return ResponseResult.okResult(LocationVo.builder()
                .lives(weatherVo)
                .province(( locationInfo.get("province")).toString())
                .city((locationInfo.get("city")).toString()).build());
    }

}
